<?php
if (!defined("HB_PATH")) die("Donot request this file directly!");

class HB_Option {
	private var $_cache;
	
	function __construct() {
		//register the database table
		db_register_table("option");
		
		//initialize the cache array;
		$this->_cache = array();
	}
	
	public function get($name, $nocache = false) {
		if ($nocache || !isset($this->_cache[$name]) {
			global $hbdb;
			//load the option value from database 
			$value = $hbdb->get_var("SELECT value FROM $hbdb->option WHERE name = '$name'");
			if (is_null($value)) {
				//option name not found
				return NULL;
			} else {
				$this->_cache[$name] = $this->_decode($value);
			}
		}
		return $this->_cache[$name];
	}
	
	public function set($name, $value) {
		global $hbdb;
		
		//test whether $name is a new key
		if (isset($this->_cache[$name] || $hbdb->get_var("SELECT COUNT(*) FROM $hbdb->option WHERE name = '$name'") > 0) {
			$key_existed = true;
		} else $key_existed = false;
		
		if (is_null($value) && $key_existed) {
			//perform an option deleting
			
			//remove the record from DB
			$hbdb->query("DELETE FROM $hbdb->option WHERE name = '$name'");
			// $hbdb->rows_affected will be > 0
			//clean the cache
			unset($this->_cache[$name]);
			return true;
		}
		
		//set the cache first :)
		$this->_cache[$name] = $value;
		$value = $this->_encode($value);
		if ($key_existed) {
			//update db
			$sql = "UPDATE $hbdb->option SET value = '$value' WHERE name = '$name'";
		} else {
			$sql = "INSERT INTO $hbdb->option (name,value) VALUES ('$name','$value')";
		}
		$hbdb->query($sql);
		return true;
	}
	
	private function _decode($val) {
		return unserialize($val);
	}
	
	private function _encode($val) {
		return serialize($val);
	}
	
}

$options = new HB_Option;
?>